﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using CUWo.App.CustomControl;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CUWo.App.WoControls
{
    public partial class WoUserCenterEmail : UserControl
    {
        private bool flag;
        private Storyboard story;

        public WoUserCenterEmail()
        {
            InitializeComponent();
            //
            this.progressBar.Visibility = Visibility.Collapsed;
            this.gridNavigate.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 是否开通沃邮箱
        /// <para>开通则调用登录接口</para>
        /// <para>未开通则调用注册接口</para>
        /// </summary>
        public void IsEnabledWoEmail()
        {
            RomInfo item = RomHelper.GetRomInfo();
            if (!(item != null && !string.IsNullOrWhiteSpace(item.Mobile)))
            {
                MessageToastManager.Show("未登录，请登录！", MessageToastLevel.Warn);
                return;
            }

            string mobileNumber = item.Mobile;            
            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.EmailIsOpen().GetUrl(mobileNumber);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageEmailIsOpen activeInfo = JSONHelper.Deserialize<JsonResultMessageEmailIsOpen>(decryptStringResult);
                            if (activeInfo != null)
                            {
                                if (activeInfo.Msg != null)
                                {
                                    if (activeInfo.Msg.MessageErrors != null && activeInfo.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(activeInfo.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (activeInfo.Msg.MessageWarns != null && activeInfo.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(activeInfo.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (activeInfo.Msg.MessagePrompts != null && activeInfo.Msg.MessagePrompts.Count > 0)
                                        {
                                            MessageToastManager.Show("正在进入邮箱，请稍候...");
                                            this.RedirectEmailLoginAddress(mobileNumber);
                                        }
                                    }
                                }
                            }

                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }

        /// <summary>
        /// 跳转至登录页
        /// </summary>
        /// <param name="mobile"></param>
        private void RedirectEmailLoginAddress(string mobileNumber)
        {
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.EmailSignUrl().GetUrl(mobileNumber);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageEmailSignUrl jsonResult = JSONHelper.Deserialize<JsonResultMessageEmailSignUrl>(decryptStringResult);
                            if (jsonResult != null)
                            {
                                if (jsonResult.Msg != null)
                                {
                                    if (jsonResult.Msg.MessageErrors != null && jsonResult.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (jsonResult.Msg.MessageWarns != null && jsonResult.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (jsonResult.Msg.MessagePrompts != null && jsonResult.Msg.MessagePrompts.Count > 0)
                                        {
                                            if (string.IsNullOrWhiteSpace(jsonResult.InBoxUrl))
                                            {
                                                MessageToastManager.Show("邮箱登录地址为空！", MessageToastLevel.Error);
                                            }
                                            else
                                            {
                                                this.progressBar.Visibility = Visibility.Visible;
                                                this.webBrowser.Navigate(new Uri(jsonResult.InBoxUrl,UriKind.Absolute));
                                            }
                                        }
                                    }
                                }
                            }

                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }


        private void ImageBack_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                this.webBrowser.InvokeScript("eval", new string[] { "onload=function() {if(history.length>0){window.external.notify('back')}else{window.external.notify('-1')}}" });
                this.webBrowser.InvokeScript("eval", new string[] { "onload()" });
            }
            catch
            {
            }
           
        }

        private void ImageSync_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                this.webBrowser.InvokeScript("eval", new string[] { "history.go(0)" });
            }
            catch
            {
            }
        }

        private void ImageNext_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                this.webBrowser.InvokeScript("eval", new string[] { "onload=function() {var i=1;if(history.length>0){window.external.notify('forward')}else{window.external.notify('1')}}" });
                this.webBrowser.InvokeScript("eval", new string[] { "onload()" });
            }
            catch { }
        }

        private void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            if (e.Value == "forward")
            {
                this.webBrowser.InvokeScript("eval", new string[] { "history.go(1)" });
            }
            if (e.Value == "back")
            {
                this.webBrowser.InvokeScript("eval", new string[] { "history.go(-1)" });
            }
        }

        private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            this.gridNavigate.Visibility = Visibility.Collapsed;
            this.progressBar.Visibility = Visibility.Visible;
        }

        private void webBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            this.gridNavigate.Visibility = Visibility.Visible;
            this.progressBar.Visibility = Visibility.Collapsed;
        }

        private void OpenMenuStory()
        {
            try
            {
                //
                this.story = new Storyboard();
                DoubleAnimation animation = new DoubleAnimation();
                this.gridNavigate.Projection = new PlaneProjection();
                this.story.Completed += story_Completed;
                animation.Duration = (Duration)TimeSpan.FromSeconds(0.5);
                animation.To = -20.0;
                animation.From = 0.0;
                Storyboard.SetTarget(animation, this.gridNavigate.Projection);
                Storyboard.SetTargetProperty(animation, new PropertyPath("(PlaneProjection.LocalOffsetY)", new object[0]));
                this.story.Children.Add(animation);
                if (this.LayoutRoot.Resources.Contains("2345"))
                {
                    this.LayoutRoot.Resources.Remove("2345");
                    this.LayoutRoot.Resources.Add("2345", this.story);
                    this.story.Begin();
                }
                else
                {
                    this.LayoutRoot.Resources.Add("2345", this.story);
                    this.story.Begin();
                }
            }
            catch (Exception)
            {
            }
        }

        void story_Completed(object sender, EventArgs e)
        {
            
        }

     

        private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!this.flag)
            {
                this.OpenMenuStory();
                this.flag = true;
            }
            else
            {
                this.story.Stop();
                this.story.Children.Clear();
                this.story = null;
                this.flag = false;
            }

        }

    }
}
